package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.business.rule.RuleBusinessLogger;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasListGroupEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasFormDataEsModel;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.SaasParticularAttributePoJo;
import com.xbongbong.paas.help.FormDataListSearchHelp;
import com.xbongbong.parent.help.ListGroupHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasListGroupModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.ButtonExtraPojo;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.ShareConditionFormatPojo;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.imports.CellTitlePojo;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.RowGroupPojo;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.service.PaasCommentService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.RangeScreenConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.errorcodes.CustomerCommunicateErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainInLinkItemDTO;
import com.xbongbong.pro.log.pojo.dto.RuleBusinessLogDTO;
import com.xbongbong.pro.suppliercommunicate.pojo.dto.SupplierCommunicateDeleteBatchDTO;
import com.xbongbong.pro.suppliercommunicate.pojo.dto.SupplierCommunicateUpdateBatchDTO;
import com.xbongbong.pro.suppliercommunicate.pojo.dto.SupplierCommunicateUpdateByBusinessRuleDTO;
import com.xbongbong.pro.suppliercommunicate.pojo.dto.SupplierCommunicateUpdateDTO;
import com.xbongbong.pro.suppliercommunicate.pojo.dto.SupplierDynamicAddDTO;
import com.xbongbong.pro.suppliercommunicate.pojo.vo.SupplierCommunicateDeleteBatchVO;
import com.xbongbong.pro.suppliercommunicate.pojo.vo.SupplierCommunicateUpdateBatchVO;
import com.xbongbong.pro.webdetail.pojo.CommunicateLeftDetailPojo;
import com.xbongbong.pro.webdetail.pojo.vo.CommunicateDetailVO;
import com.xbongbong.pro.weblist.pojo.CustomerCommunicatePojo;
import com.xbongbong.pro.weblist.pojo.vo.CommunicateVO;
import com.xbongbong.saas.analytical.impl.SupplierCommunicateValidateAnalyticalServiceImpl;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ext.SupplierCommunicateEntityExt;
import com.xbongbong.saas.enums.BusinessCommentEnum;
import com.xbongbong.saas.enums.ListTopButtonEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.SaasSubButtonEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.base.CommunicateBaseEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.help.ImportHelper;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.SupplierCommunicateModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.service.LikeService;
import com.xbongbong.saas.service.SupplierCommunicateService;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author long.rao
 * @version v1.0
 * @date 2019/1/29 11:36
 * @since v1.0
 */
@Service("supplierCommunicateService")
public class SupplierCommunicateServiceImpl implements SupplierCommunicateService {

    private static final Logger LOG = LoggerFactory.getLogger(SupplierCommunicateServiceImpl.class);

    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasFormDataEsModel paasFormDataEsModel;
    @Resource
    private PaasCommentService paasCommentService;
    @Resource
    private LikeService likeService;
    @Resource
    private UserModel userModel;
    @Resource
    private SupplierCommunicateModel supplierCommunicateModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private ListGroupHelp listGroupHelp;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private ImportHelper importHelper;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    @Lazy
    private RuleBusinessLogger ruleBusinessLogger;
    @Resource
    @Lazy
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private PaasListGroupModel paasListGroupModel;
    @Resource
    private FormDataListSearchHelp formDataListSearchHelp;
    @Resource
    private SupplierCommunicateValidateAnalyticalServiceImpl supplierCommunicateAnalyticalService;
    @Resource
    private IndexTypeModel indexTypeModel;

    @Override
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        supplierCommunicateAnalyticalService.beforeSave(validateDataDTO);
    }

    @Override
    public void afterSave(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        PaasFormDataEntity paasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        JSONObject data = paasFormDataEntity.getData();
        Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(data, SupplierCommunicateEnum.SUPPLIER_ID.getAttr(), 0L);
        Long communicateTime = FastJsonHelper.getLongOrDefaultFromFormData(data, SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr(), 0L);
        PaasFormDataEntityExt supplierEntityExt = supplierModel.getByKey(supplierId, saasFormSaveDTO.getCorpid());
        Long lastConnectTime = FastJsonHelper.getLongOrDefaultFromFormData(supplierEntityExt.getData(), SupplierEnum.LAST_CONNECT_TIME.getAttr(), 0L);
        if (lastConnectTime < communicateTime){
            if (communicateTime > DateTimeUtil.getInt()) {
                communicateTime = DateTimeUtil.getInt();
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(SupplierEnum.LAST_CONNECT_TIME.getAttr(), communicateTime);
            UpdateDataEntity updateData = ExplainUtil.getUpdateData(supplierId, jsonObject, saasFormSaveDTO.getCorpid());
            supplierModel.updateBatch(Collections.singletonList(updateData), saasFormSaveDTO.getCorpid());
        }
        // 供应商跟进记录@指定人员
        List<String> atUserIds = saasFormSaveDTO.getSaasNeedRedundantAttrPoJo().getAtUserIds();
        if (Objects.isNull(atUserIds)) {
            JSONObject obj = saasFormSaveDTO.getNewPaasFormDataEntity().getData();
            JSONArray jsonArray = obj.getJSONArray(CustomerCommunicateEnum.AT_USERNAME.getAttr());
            if (Objects.nonNull(jsonArray)) {
                atUserIds = JSONArray.parseArray(jsonArray.toJSONString(),String.class);
            }
        }
        if (Objects.nonNull(atUserIds) && atUserIds.size() > 0) {
            atUserIds.remove(saasFormSaveDTO.getLoginUser().getUserId());
            customerCommunicateService.pushCustomerCommounicate(saasFormSaveDTO.getLoginUser(), saasFormSaveDTO.getBusinessType(), saasFormSaveDTO.getCorpid(), atUserIds, paasFormDataEntity, paasFormDataEntity.getId(), false);
        }
    }



    @Override
    public void formatAddExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(attr, SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr())) {
                SaasParticularAttributePoJo saasParticularAttributePoJo = fieldAttrEntity.getSaasParticularAttributePoJo();
                saasParticularAttributePoJo = saasParticularAttributePoJo == null ? new SaasParticularAttributePoJo() : saasParticularAttributePoJo;
                Integer now = DateUtil.getInt();
                DefaultAttrPoJo defaultAttrPoJo = fieldAttrEntity.getDefaultAttr();
                defaultAttrPoJo.setDefaultValue(DateUtil.getString(now, DateUtil.SDFYMDHM));
                fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
                saasParticularAttributePoJo.setDateLimit(DateTimeUtil.getTodayInt() + TimeConstant.SECONDS_PER_DAY);
                saasParticularAttributePoJo.setLimitType(true);
                fieldAttrEntity.setSaasParticularAttributePoJo(saasParticularAttributePoJo);
            }
        }
    }

    @Override
    public CommunicateVO list(FormDataListDTO formDataListDTO) throws XbbException {
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
        List<ConditionsEntityExt> permissionConditions = saasListDataPermissionHelp.listDataPermission(false, formDataListDTO.getConditions(), formDataListDTO.getLoginUser(), XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getCode(), formDataListDTO.getSubBusinessType());
        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
        formDataListDTO.setSharePermission(sharePermission);
        // app端范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(formDataListDTO.getConditions(), userEntity, XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        setCondition(formDataListDTO);
        rangeScreen(formDataListDTO);
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formDataListDTO.getFormId(), formDataListDTO.getCorpid());
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        formDataListDTO.setMenuId(paasFormExplainEntity.getMenuId());
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
        explainList.forEach((item) -> {
            explainMap.put(item.getAttr(), item);
        });
        FieldAttrEntity fieldAttrEntity = explainMap.get(SupplierCommunicateEnum.TYPE.getAttr());
        formDataListDTO.setExplainMap(explainMap);
        //默认排序 字段显示
        formDataListSearchHelp.setListColumn(formDataListDTO);
        Map<String, String> sortMap = formDataListDTO.getSortMap();
        if (Objects.isNull(sortMap) || sortMap.isEmpty()) {
            Map<String, String> defaultSort = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            defaultSort.put("field", SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr());
            defaultSort.put("sort", SortOrder.DESC.name());
            formDataListDTO.setSortMap(defaultSort);
        }
        formDataListDTO.setSearchSubForm(false);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(formDataListDTO.getCorpid(), formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        PaasFormDataEsListVO formDataListVO = paasFormDataEsModel.list(formDataListDTO, indexTypeEnum);
        List<Long> dataIdIn = new ArrayList<>();
        List<String> userIdIn = new ArrayList<>();
        for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()) {
            dataIdIn.add(entity.getDataId());
            userIdIn.add(entity.getCreatorId());
        }
        dataIdIn.add(-1L);
        Map<Long,Integer> commnetCountMap = paasCommentService.getCommnetCountMap(dataIdIn,formDataListDTO.getCorpid(),BusinessCommentEnum.SUPPLIER_COMMUNICATE.getCode());
        Map<Long,Integer> likeCountMap = likeService.getLikeCountMap(dataIdIn,formDataListDTO.getCorpid(),BusinessCommentEnum.SUPPLIER_COMMUNICATE.getCode());
        List<Long> hasCommentIdList = paasCommentService.hasMyComment(dataIdIn,formDataListDTO.getCorpid(),BusinessCommentEnum.SUPPLIER_COMMUNICATE.getCode(),formDataListDTO.getUserId());
        List<Long> hasLikeIdList = likeService.hasMyLike(dataIdIn,formDataListDTO.getCorpid(),BusinessCommentEnum.SUPPLIER_COMMUNICATE.getCode(),formDataListDTO.getUserId());
        List<UserEntity> creatorList = userModel.getByUserIdIn(formDataListDTO.getCorpid(), userIdIn, false);
        Map<String, UserEntity> creatorMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (UserEntity creator : creatorList) {
            creatorMap.put(creator.getUserId(), creator);
        }
        List<CustomerCommunicatePojo> customerCommunicatePojoList = new ArrayList<>();
        for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()) {
            CustomerCommunicatePojo customerCommunicatePojo = new CustomerCommunicatePojo();
            JSONObject data = entity.getData();
            JSONArray images = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, SupplierCommunicateEnum.IMAGES.getAttr(), new JSONArray());
            Integer communicateBuisenssType = data.getInteger(CommunicateBaseEnum.COMMUNICATE_BUSINESS_TYPE.getAttr());
            try {
                customerCommunicatePojo.setId(entity.getId());
                customerCommunicatePojo.setCommunicateTime(DateUtil.getString(data.getInteger(SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr()), DateUtil.SDFYMDHM));
                customerCommunicatePojo.setCustomerId(data.getLong(SupplierCommunicateEnum.SUPPLIER_ID.getAttr()));
                customerCommunicatePojo.setCustomerName(data.getString(SupplierCommunicateEnum.SUPPLIER_NAME_LINK_TEXT.getAttr()));
                customerCommunicatePojo.setMemo(data.getString(SupplierCommunicateEnum.MEMO.getAttr()));
                String typeStr = "";
                Object type = ItemUtil.getCustomItemList(fieldAttrEntity, data);
                if (Objects.nonNull(type)) {
                    typeStr = type.toString();
                }
                customerCommunicatePojo.setType(typeStr);
                if (!Objects.isNull(communicateBuisenssType)) {
                    //方便前端跳转详情
                    String businessName = XbbRefTypeEnum.getByCode(communicateBuisenssType).getName();
                    customerCommunicatePojo.setBusinessName(businessName + "（" + data.getString(SupplierCommunicateEnum.COMMUNICATE_BUSINESS_LINK_TEXT.getAttr()) + "）");
                    customerCommunicatePojo.setBusinessType(data.getInteger(SupplierCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr()));
                    customerCommunicatePojo.setBusinessId(data.getLong(SupplierCommunicateEnum.COMMUNICATE_BUSINESS.getAttr()));
                }
                UserEntity creator = creatorMap.get(entity.getCreatorId());
                if (Objects.nonNull(creator)) {
                    customerCommunicatePojo.setUserId(creator.getUserId());
                    customerCommunicatePojo.setUserName(creator.getName());
                    customerCommunicatePojo.setUserAvatar(creator.getAvatar());
                } else {
                    customerCommunicatePojo.setUserId(data.getString(SupplierCommunicateEnum.USER_ID.getAttr()));
                    customerCommunicatePojo.setUserName(data.getString(SupplierCommunicateEnum.USER_NAME.getAttr()));
                    customerCommunicatePojo.setUserAvatar(data.get(SupplierCommunicateEnum.USER_AVATAR.getAttr()));
                }
                customerCommunicatePojo.setCommentCount(commnetCountMap.getOrDefault(entity.getDataId(),0));
                customerCommunicatePojo.setLikeCount(likeCountMap.getOrDefault(entity.getDataId(),0));
                customerCommunicatePojo.setHasMyComment(hasCommentIdList.contains(entity.getDataId()) ? 1 : 0);
                customerCommunicatePojo.setHasMyLike(hasLikeIdList.contains(entity.getDataId()) ? 1 : 0);
                customerCommunicatePojo.setImages(images);
                customerCommunicatePojo.setHasMyComment(hasCommentIdList.contains(entity.getDataId()) ? 1 : 0);
                customerCommunicatePojo.setHasMyLike(hasLikeIdList.contains(entity.getDataId()) ? 1 : 0);
                JSONArray supplierContact = data.getJSONArray(SupplierCommunicateEnum.SUPPLIER_CONTACT_NAME_LINK_TEXT.getAttr());
                if (supplierContact != null && supplierContact.size() > 0) {
                    customerCommunicatePojo.setContact(supplierContact);
                }
                String communicateVideo = data.getString(CustomerCommunicateEnum.VIDEO.getAttr());
                if (!Objects.isNull(communicateVideo) && !"".equals(communicateVideo)) {
                    customerCommunicatePojo.setIfVideo(true);
                }

                String communicateFile = data.getString(CustomerCommunicateEnum.FILE.getAttr());
                if (!Objects.isNull(communicateFile) && !"".equals(communicateFile)) {
                    customerCommunicatePojo.setIfFile(true);
                }
                String addressStr;
                JSONObject addressJsonObject = data.getJSONObject(CommunicateBaseEnum.ADDRESS.getAttr());
                if (Objects.nonNull(addressJsonObject)) {
                    try {
                        addressStr = addressJsonObject.getString(PaasConstant.PROVINCE) + addressJsonObject.getString(PaasConstant.CITY) + addressJsonObject.getString(PaasConstant.DISTRICT) + addressJsonObject.getString(PaasConstant.ADDRESS);
                    }catch (Exception e){
                        addressStr = "";
                    }
                    customerCommunicatePojo.setAddress(addressStr);
                }

                customerCommunicatePojoList.add(customerCommunicatePojo);
            } catch (Exception e) {

            }
        }
        CommunicateVO communicateVO = new CommunicateVO();
        communicateVO.setResultMap(customerCommunicatePojoList);
        communicateVO.setPageHelper(formDataListVO.getPageHelper());
        setTopPermissions(formDataListDTO, communicateVO);
        return communicateVO;
    }

    @Override
    public CommunicateDetailVO detail(FormDataGetDTO formDataGetDTO) throws XbbException{
        PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(formDataGetDTO.getFormId(),formDataGetDTO.getCorpid());
        Map<String,String> typeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<FieldAttrEntity> explainList = JSONArray.parseArray(explainEntity.getExplains(), FieldAttrEntity.class);
        FieldAttrEntity fieldAttrEntity = new FieldAttrEntity();
        for (FieldAttrEntity entity : explainList) {
            if (Objects.equals(entity.getAttr(), SupplierCommunicateEnum.TYPE.getAttr())) {
                fieldAttrEntity = entity;
                break;
            }
        }
        SupplierCommunicateEntityExt entityExt = supplierCommunicateModel.getByKey(formDataGetDTO.getDataId(),formDataGetDTO.getCorpid());
        CommunicateDetailVO communicateDetailVO = new CommunicateDetailVO();
        JSONArray detailPermissionSet = new JSONArray();
        detailPermissionSet.addAll(Arrays.asList("copy","edit","del"));
        communicateDetailVO.setDetailPermissionSet(detailPermissionSet);
        CommunicateLeftDetailPojo communicateLeftDetailPojo = new CommunicateLeftDetailPojo();
        JSONObject data = entityExt.getData();
        communicateLeftDetailPojo.setId(entityExt.getId());
        communicateLeftDetailPojo.setCommunicateTime(DateUtil.getString(data.getInteger(SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr())));
        communicateLeftDetailPojo.setMemo(data.getString(SupplierCommunicateEnum.MEMO.getAttr()));
        UserEntity userEntity = userModel.getByKeyIngoreDel(entityExt.getCreatorId(),entityExt.getCorpid());
        String avatar = userEntity.getAvatar();
        avatar = avatar == null ? "" : avatar;
        communicateLeftDetailPojo.setUserId(userEntity.getUserId());
        communicateLeftDetailPojo.setUserAvatar(Collections.singletonList(avatar));
        communicateLeftDetailPojo.setUserName(userEntity.getName());
        String typeStr = "";
        Object type = ItemUtil.getCustomItemList(fieldAttrEntity, data);
        if (Objects.nonNull(type)) {
            typeStr = type.toString();
        }
        communicateLeftDetailPojo.setType(typeStr);
        communicateLeftDetailPojo.setImages(data.getJSONArray(SupplierCommunicateEnum.IMAGES.getAttr()));
        communicateLeftDetailPojo.setAddress(data.getString(SupplierCommunicateEnum.ADDRESS.getAttr()));
        communicateLeftDetailPojo.setIfLike(likeService.getIfLike(formDataGetDTO.getCorpid(),BusinessCommentEnum.SUPPLIER_COMMUNICATE.getCode(),entityExt.getAppId(),entityExt.getId(),userEntity.getUserId()) ? 1 : 0);
        communicateLeftDetailPojo.setCommentCount(paasCommentService.getCount(formDataGetDTO.getCorpid(),BusinessCommentEnum.SUPPLIER_COMMUNICATE.getCode(),entityExt.getAppId(),entityExt.getId()));
        communicateLeftDetailPojo.setLikeCount(likeService.getCount(formDataGetDTO.getCorpid(),BusinessCommentEnum.SUPPLIER_COMMUNICATE.getCode(),entityExt.getAppId(),entityExt.getId(), formDataGetDTO.getUserId()));
        communicateLeftDetailPojo.setContact(data.getJSONArray(SupplierCommunicateEnum.SUPPLIER_CONTACT_NAME_LINK_TEXT.getAttr()));
        Integer communicateBuisenssType = data.getInteger(SupplierCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr());
        if (!Objects.isNull(communicateBuisenssType)) {
            //方便前端跳转详情
            String businessName = XbbRefTypeEnum.getByCode(communicateBuisenssType).getName();
            communicateLeftDetailPojo.setCommunicateBusinessName(businessName + "（" + data.getString(SupplierCommunicateEnum.COMMUNICATE_BUSINESS_LINK_TEXT.getAttr()) + "）");
        }
        String supplierName = data.getString(SupplierCommunicateEnum.SUPPLIER_NAME_LINK_TEXT.getAttr());
        supplierName = supplierName == null ? "" : supplierName;
        String addressStr;
        JSONObject addressJsonObject = data.getJSONObject(CommunicateBaseEnum.ADDRESS.getAttr());
        if (Objects.nonNull(addressJsonObject)) {
            try {
                addressStr = addressJsonObject.getString(PaasConstant.PROVINCE) + addressJsonObject.getString(PaasConstant.CITY) + addressJsonObject.getString(PaasConstant.DISTRICT) + addressJsonObject.getString(PaasConstant.ADDRESS);
            }catch (Exception e){
                addressStr = "";
            }
            communicateLeftDetailPojo.setAddress(addressStr);
        }
        communicateLeftDetailPojo.setMainBusinessName(supplierName);
        communicateDetailVO.setHead(communicateLeftDetailPojo);
        return communicateDetailVO;
    }

    @Override
    public SupplierCommunicateDeleteBatchVO deleteBatch(SupplierCommunicateDeleteBatchDTO supplierCommunicateDeleteBatchDTO) throws XbbException {
        SupplierCommunicateDeleteBatchVO supplierCommunicateDeleteBatchVO = new SupplierCommunicateDeleteBatchVO();
        try {
            List<Long> idIn = supplierCommunicateDeleteBatchDTO.getDataIdList();
            String corpid = supplierCommunicateDeleteBatchDTO.getCorpid();
            List<String> name= new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (!idIn.isEmpty()) {
                //查询名称
                BoolQueryBuilder builder = boolQuery();
                // 添加corpid,formId,del
                builder.filter(termQuery("corpid.keyword", corpid));
                builder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                builder.filter(termsQuery(StringConstant.DATA_ID, idIn));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.DATA_ID);
                fieldList.add(StringConstant.JSON_DATA);
                List<PaasFormDataEntityExt> noList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_SUPPLIER_COMMUNICATE, builder, PaasFormDataEntityExt.class, fieldList);
                for(PaasFormDataEntityExt entityExt : noList){
                    JSONObject data = entityExt.getData();
                    String sheetName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierCommunicateEnum.SUPPLIER_NAME_LINK_TEXT.getAttr(), "");
                    name.add(sheetName);
                }
                if(!idIn.isEmpty()) {
                    if(BasicConstant.ONE.equals(supplierCommunicateDeleteBatchDTO.getSingleFlag())
                            && BasicConstant.ONE.equals(idIn.size())){
                        supplierCommunicateModel.deleteByKey(idIn.get(0),corpid);
                    }else {
                        supplierCommunicateModel.deleteBatch(idIn, corpid);
                    }
                    supplierCommunicateDeleteBatchVO.setDeleteIds(idIn);
                }
            }
            OperateTypeEnum operateTypeEnum = OperateTypeEnum.DELETE;
            if (Objects.equals(1, supplierCommunicateDeleteBatchDTO.getIsBusinessRule())) {
                operateTypeEnum = OperateTypeEnum.RULE_DELETE;
            }
            //生成删除日志(区分单个删除和批量删除)
            String userId = supplierCommunicateDeleteBatchDTO.getUserId();
            String userName = supplierCommunicateDeleteBatchDTO.getLoginUserName();
            String nameStr = StringUtils.join(name, "，");
            if(idIn.size() > 1){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_DELETE_FORM_DETAIL), userName, XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getName(), idIn.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(SupplierCommunicateEnum.SUPPLIER_NAME_LINK_TEXT.getAttrName());
                infoArrPojo.setContent(nameStr);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.SUPPLIER_COMMUNICATE, operateTypeEnum,
                        "", "", memo, supplierCommunicateDeleteBatchDTO.getHttpHeader());
            } else if (Objects.equals(idIn.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), userName, XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getName(), nameStr);
                mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.SUPPLIER_COMMUNICATE, operateTypeEnum,
                        idIn.get(0).toString(), nameStr, memo, supplierCommunicateDeleteBatchDTO.getHttpHeader());
            }
        } catch (Exception e) {
            LOG.error("supplierCommunicateServiceImpl.deleteBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return supplierCommunicateDeleteBatchVO;
    }

    @Override
    public FormDataAddDTO formatExcelValue(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList, RowGroupPojo rowGroupPojo, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        BeanUtil.copyProperties(importFormDataDTO, formDataAddDTO);
        formDataAddDTO.setSerialNo("");
        JSONObject dataJson = new JSONObject();
        List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
        // 分组的第一条数据作为给实体对象赋值的数据
        List<CellValuePojo> cellValueList = rowValueList.get(0);
        for (FieldAttrEntityForImport fieldAttr : fieldAttrList) {
            String attr = fieldAttr.getAttr();
            Integer fieldType = fieldAttr.getFieldType();
            String attrName = fieldAttr.getAttrName();
            Integer columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
                importHelper.formatSubFormValue4Import(rowValueList, titlePojoList, importFormDataDTO, fieldAttr, dataJson);
            } else {
                if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                    continue;
                }
                if (ImportHelper.commonHandleFieldType.contains(fieldAttr.getFieldType())) {
                    importHelper.formatCommonField(dataJson, fieldAttr, cellValue);
                } else {
                    if (Objects.equals(attr, CommunicateBaseEnum.CONTACT.getAttr())) {
                        importHelper.formatLinkBusinessValue4Import(dataJson, fieldAttr, cellValue);
                    } else if (Objects.equals(fieldType, FieldTypeEnum.SERIALNO.getType())) {
                        formDataAddDTO.setSerialNo(cellValue.toString());
                    } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA.getType())) {
                        importHelper.formatLinkData(cellValue, fieldAttr, dataJson);
                    } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA_MULTI.getType())) {
                        importHelper.formatLinkDataMulti(cellValue, importFormDataDTO, fieldAttr, dataJson);
                    } else {
                        dataJson.put(attr, cellValue);
                    }
                }
            }
        }
        formDataAddDTO.setDataList(dataJson);
        return formDataAddDTO;
    }

    @Override
    public void formatLinkAddExplain(HandlerExplainInLinkItemDTO handlerExplainInLinkItemDTO) throws XbbException {
        JSONObject linkFormData = handlerExplainInLinkItemDTO.getLinkFormData();
        Long linkDataId = handlerExplainInLinkItemDTO.getLinkDataId();
        List<FieldAttrEntity> explainList = handlerExplainInLinkItemDTO.getExplainList();
        FieldAttrEntity linkSupplierField = new FieldAttrEntity();
        FieldAttrEntity linkBusinessField = new FieldAttrEntity();
        FieldAttrEntity linkContactField = new FieldAttrEntity();
        for(FieldAttrEntity fieldAttrEntity :explainList) {
            if (Objects.equals(fieldAttrEntity.getAttr(), SupplierCommunicateEnum.SUPPLIER_ID.getAttr())) {
                linkSupplierField = fieldAttrEntity;
            }
            if (Objects.equals(fieldAttrEntity.getAttr(), SupplierCommunicateEnum.SUPPLIER_CONTACT.getAttr())) {
                linkContactField = fieldAttrEntity;
            }
            if (Objects.equals(fieldAttrEntity.getAttr(), SupplierCommunicateEnum.COMMUNICATE_BUSINESS.getAttr())) {
                linkBusinessField = fieldAttrEntity;
            }
        }
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(handlerExplainInLinkItemDTO.getLinkBusinessType());
        switch (redundantTemplateTypeEnum) {
            case SUPPLIER:
                String supplierName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                linkSupplierField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, supplierName));
                break;
            case SUPPLIER_CONTACT:
                String contactName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, SupplierContactEnum.NAME.getAttr(), "");
                linkContactField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, contactName));
                JSONArray linkSupplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(linkFormData, SupplierContactEnum.SUPPLIER_ID.getAttr(), new JSONArray());
                linkSupplierField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkSupplierArr));
                break;
            case PURCHASE:
                String purchaseNo = handlerExplainInLinkItemDTO.getPaasFormDataEntityExt().getSerialNo();
                purchaseNo = purchaseNo == null ? "" : purchaseNo;
                linkBusinessField.setDefaultAttr(saasUpdateHelp.getDefaultLinkPojo(linkDataId, purchaseNo, redundantTemplateTypeEnum.getCode()));
                JSONArray purchaseLinkSupplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(linkFormData, PurchaseEnum.SUPPLIER_ID.getAttr(), new JSONArray());
                linkSupplierField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(purchaseLinkSupplierArr));
                break;
            default:
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
    }



    @Override
    public void setCondition(FormDataListDTO formDataListDTO) throws XbbException{
        if(formDataListDTO.getListGroupId() != null){
            PaasListGroupEntity paasListGroupEntity ;
            if (formDataListDTO.getListGroupId() != null && Objects.equals(formDataListDTO.getDefaultGroup(), 0)) {
                paasListGroupEntity = paasListGroupModel.getByKey(formDataListDTO.getListGroupId(), formDataListDTO.getCorpid());
            } else {
                paasListGroupEntity = listGroupHelp.getDefaultGroup(formDataListDTO);
            }
            if (paasListGroupEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.LIST_GROUP_NOT_EXIST);
            }
            List<ConditionsEntityExt> listGroupConditionList = JSONArray.parseArray(paasListGroupEntity.getJsonData(), ConditionsEntityExt.class);
            if(listGroupConditionList != null && !listGroupConditionList.isEmpty()){
                List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
                conditionList.addAll(listGroupConditionList);
                formDataListDTO.setConditions(conditionList);
            }
        }
        if (formDataListDTO.getCommonFilter() != null){
            List<ConditionsEntityExt> conditionsEntityExtList = formDataListDTO.getConditions();
            conditionsEntityExtList = conditionsEntityExtList == null ? new ArrayList<>() : conditionsEntityExtList;
            JSONObject commonFilter = formDataListDTO.getCommonFilter();
            for (Map.Entry<String,Object> entry : commonFilter.entrySet()){
                if (Objects.isNull(entry.getValue()) || (Objects.nonNull(entry.getValue()) && StringUtil.isEmpty(entry.getValue().toString()))){
                    continue;
                }
                ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                conditionsEntityExt.setAttr(entry.getKey());
                if (Objects.isNull(SupplierCommunicateEnum.getByAttr(entry.getKey()))) {
                    continue;
                }
                Integer fieldType = SupplierCommunicateEnum.getByAttr(entry.getKey()).getFieldType();
                conditionsEntityExt.setFieldType(fieldType);
                if (Objects.equals(fieldType,FieldTypeEnum.DATETIME.getType())){
                    conditionsEntityExt.setSymbol(ConditionEnum.RANGE.getSymbol());
                    List<String> stringList = JSONArray.parseArray(JSONArray.toJSONString(entry.getValue()),String.class);
                    List<Object> valueList = new ArrayList<>();
                    valueList.add(DateTimeUtil.getInt(stringList.get(0),DateTimeUtil.SDFDate));
                    valueList.add(DateTimeUtil.getInt(stringList.get(1),DateTimeUtil.SDFDate) + TimeConstant.SECONDS_PER_DAY);
                    conditionsEntityExt.setValue(valueList);
                }else if (Objects.equals(fieldType,FieldTypeEnum.COMBO.getType())){
                    conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(entry.getValue()));
                }else {
                    conditionsEntityExt.setSymbol(ConditionEnum.LIKE.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(entry.getValue()));
                }
                conditionsEntityExtList.add(conditionsEntityExt);
            }
            formDataListDTO.setConditions(conditionsEntityExtList);
        }
    }

    @Override
    public void dataConsistencyUpdateSupplier(String corpid, Long dataId, String name) throws XbbException {
        try {
            BoolQueryBuilder filter = boolQuery()
                    .filter(termQuery("corpid.keyword", corpid))
                    .filter(termQuery("del", 0))
                    .filter(termQuery(SupplierCommunicateEnum.getEsAttr4Keyword(SupplierCommunicateEnum.SUPPLIER_ID), dataId));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> esEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_SUPPLIER_COMMUNICATE, filter, PaasFormDataEntityExt.class, fieldList);
            Set<Long> ids = new HashSet<>();
            for (PaasFormDataEntityExt esEntity : esEntities) {
                ids.add(esEntity.getDataId());
            }
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("idIn", ids);
            param.put("del", 0);
            List<SupplierCommunicateEntityExt> supplierCommunicateList = supplierCommunicateModel.findEntitys(param);

            if (Objects.nonNull(supplierCommunicateList) && !supplierCommunicateList.isEmpty()) {
                List<SupplierCommunicateUpdateDTO> purchaseUpdateDTOList = new ArrayList<>();
                for (SupplierCommunicateEntityExt entityExt : supplierCommunicateList) {
                    SupplierCommunicateUpdateDTO supplierContactUpdateDTO = new SupplierCommunicateUpdateDTO();
                    supplierContactUpdateDTO.setId(entityExt.getId());
                    JSONObject data = new JSONObject();
                    data.put(SupplierCommunicateEnum.SUPPLIER_NAME_LINK_TEXT.getAttr(), name);
                    supplierContactUpdateDTO.setData(data);
                    purchaseUpdateDTOList.add(supplierContactUpdateDTO);
                }
                SupplierCommunicateUpdateBatchDTO supplierContactUpdateBatchDTO = new SupplierCommunicateUpdateBatchDTO();
                supplierContactUpdateBatchDTO.setCorpid(corpid);
                supplierContactUpdateBatchDTO.setSupplierCommunicateList(purchaseUpdateDTOList);
                updateBatch(supplierContactUpdateBatchDTO);
            }

        } catch (Exception e) {
            LOG.error("supplierCommunicateServiceImpl.dataConsistencyUpdateSupplier 出错， corpid=" + corpid + "  contactId=" + dataId + "  contactName=" + name, e);
        }
    }

    @Override
    public void updateBatchByBusinessRule(SupplierCommunicateUpdateByBusinessRuleDTO supplierCommunicateUpdateByBusinessRuleDTO) throws XbbException {
        try {
            String corpid = supplierCommunicateUpdateByBusinessRuleDTO.getCorpid();
            List<PaasFormDataEntityExt> formDataList = supplierCommunicateUpdateByBusinessRuleDTO.getFormDataList();
            List<UpdateDataEntity> updateList = ExplainUtil.getUpdateValueByBusinessRule(formDataList, corpid, supplierCommunicateUpdateByBusinessRuleDTO.getOperations());

            if (!updateList.isEmpty()) {
                supplierCommunicateModel.updateBatch(updateList, corpid);
                RuleBusinessLogDTO businessLogDTO = new RuleBusinessLogDTO();
                BeanUtil.copyProperties(supplierCommunicateUpdateByBusinessRuleDTO, businessLogDTO);
                businessLogDTO.setFormDataList(formDataList);
                ruleBusinessLogger.writeLog(businessLogDTO, updateList);
            }
        } catch (Exception e) {
            LOG.error("supplierCommunicateService.updateFormDataByBusinessRule根据业务规则更新数据出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public void addSupplierDynamic(SupplierDynamicAddDTO supplierDynamicAddDTO) throws XbbException {
        String corpid = supplierDynamicAddDTO.getCorpid();
        Long supplierId = supplierDynamicAddDTO.getSupplierId();
        String supplierName = supplierDynamicAddDTO.getSupplierName();
        if (StringUtil.isEmpty(supplierName)) {
            //获取供应商数据
            PaasFormDataEntityExt paasFormDataEntityExt = purchaseModel.getByKey(supplierId, corpid);
            if (paasFormDataEntityExt != null) {
                supplierName =  paasFormDataEntityExt.getData().getString(SupplierEnum.SUPPLIER_NAME.getAttr());
            }
        }
        //TODO 应该是有问题的
        PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode(),corpid);
        Long appId = 0L;
        Long menuId = 0L;
        Long formId = 0L;
        if (paasFormEntity != null) {
            appId = paasFormEntity.getAppId();
            menuId = paasFormEntity.getMenuId();
            formId = paasFormEntity.getId();
        }
        // 保存入库
        SupplierCommunicateEntityExt supplierCommunicateEntityExt = new SupplierCommunicateEntityExt();
        JSONObject data = new JSONObject();
        data.put(CommunicateBaseEnum.MEMO.getAttr(),supplierDynamicAddDTO.getMemo());
        data.put(SupplierCommunicateEnum.SUPPLIER_ID.getAttr(),supplierId);
        data.put(SupplierCommunicateEnum.SUPPLIER_NAME_LINK_TEXT.getAttr(),supplierName);
        data.put(SupplierCommunicateEnum.COMMUNICATE_BUSINESS.getAttr(),supplierDynamicAddDTO.getDataId());
        data.put(SupplierCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr(),supplierDynamicAddDTO.getCommunicateBusinessType());
        data.put(SupplierCommunicateEnum.COMMUNICATE_BUSINESS_LINK_TEXT.getAttr(),supplierDynamicAddDTO.getCommunicateBusinessText());
        //"动态"数据也是跟进记录，通过设置 AUTO_GEN 为1 ，来标识这条数据是系统自动生成的，用于区分用户手动新建的跟进记录。这个flag在查询列表会用到
        data.put(SupplierCommunicateEnum.AUTO_GEN.getAttr(),1);
        data.put(SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr(),DateTimeUtil.getInt());
        supplierCommunicateEntityExt.setData(data);
        supplierCommunicateEntityExt.setCreatorId(supplierDynamicAddDTO.getUserId());
        supplierCommunicateEntityExt.setOwnerId(supplierDynamicAddDTO.getUserId());
        supplierCommunicateEntityExt.setCorpid(supplierDynamicAddDTO.getCorpid());
        supplierCommunicateEntityExt.setAppId(appId);
        supplierCommunicateEntityExt.setMenuId(menuId);
        supplierCommunicateEntityExt.setFormId(formId);
        supplierCommunicateEntityExt.setSerialNo("");
        supplierCommunicateEntityExt.setDepartmentId(0L);
        supplierCommunicateEntityExt.setFlowStatus(0);
        try {
            supplierCommunicateModel.insert(supplierCommunicateEntityExt);
        } catch (Exception e){
            LOG.error("项目日志保存失败",e);
            throw new XbbException(CustomerCommunicateErrorCodeEnum.API_ERROR_206012);
        }

    }

    @Override
    public void afterSaveForWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {

    }

    @Override
    public void afterSaveForUpdateWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {

    }

    private SupplierCommunicateUpdateBatchVO updateBatch(SupplierCommunicateUpdateBatchDTO purchaseUpdateBatchDTO) throws XbbException {
        SupplierCommunicateUpdateBatchVO supplierCommunicateUpdateBatchVO = new SupplierCommunicateUpdateBatchVO();
        try {
            String corpid = purchaseUpdateBatchDTO.getCorpid();
            List<UpdateDataEntity> updateList = new ArrayList<>();
            purchaseUpdateBatchDTO.getSupplierCommunicateList().forEach((item)->{
                updateList.add(ExplainUtil.getUpdateData(item.getId(), item.getData(), corpid));
            });
            if (!updateList.isEmpty()) {
                supplierCommunicateModel.updateBatch(updateList, corpid);
            }
        } catch (Exception e) {
            LOG.error("supplierCommunicateServiceImpl.updateBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return supplierCommunicateUpdateBatchVO;
    }

    private void setTopPermissions(FormDataListDTO formDataListDTO, CommunicateVO communicateVO) throws XbbException{
        UserVO userVO = formDataListDTO.getLoginUser();
        List<ListTopButtonEnum> topButtonEnumList = ListTopButtonEnum.getByBusinessType(formDataListDTO.getBusinessType());
        List<ButtonPojo> topButtonList = new ArrayList<>();
        PaasMenuEntity paasMenuEntity = paasMenuModel.getByKey(formDataListDTO.getMenuId(), formDataListDTO.getCorpid());
        if (Objects.isNull(paasMenuEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
        }
        for (ListTopButtonEnum topButtonEnum : topButtonEnumList) {
            if ((Objects.equals(topButtonEnum, ListTopButtonEnum.SUPPLIER_COMMUNICATE_ADD) && !userVO.getPermSet().contains(ProPermissionAliasEnum.SUPPLIER_COMMUNICATE_ADD.getAlias()))
                    || (Objects.equals(topButtonEnum, ListTopButtonEnum.SUPPLIER_COMMUNICATE_IMPORT) && !userVO.getPermSet().contains(ProPermissionAliasEnum.SUPPLIER_COMMUNICATE_IMPORT.getAlias()))
                    || (Objects.equals(topButtonEnum, ListTopButtonEnum.SUPPLIER_COMMUNICATE_EXPORT) && !userVO.getPermSet().contains(ProPermissionAliasEnum.SUPPLIER_COMMUNICATE_EXPORT.getAlias()))) {
                continue;
            }
            ButtonPojo buttonPojo = new ButtonPojo();
            BeanUtil.copyProperties(topButtonEnum.getAnEnum(), buttonPojo);
            topButtonList.add(buttonPojo);
            // 移动端列表页新建按钮
            if (Objects.equals(buttonPojo.getAttr(), SaasButtonEnum.ADD.getAttr())) {
                communicateVO.setAddPermission(true);
            }
            if (Objects.equals(topButtonEnum.getAnEnum().getAttr(), SaasButtonEnum.IMPORT.getAttr())) {
                ButtonExtraPojo buttonExtraPojo = new ButtonExtraPojo();
                buttonExtraPojo.setImportTitle(paasMenuEntity.getName());
                buttonPojo.setButtonExtra(buttonExtraPojo);
            }
            if (Objects.equals(topButtonEnum.getAnEnum().getAttr(), SaasButtonEnum.EXPORT.getAttr())) {
                List<ButtonPojo> subButtonList = new ArrayList<ButtonPojo>(){{
                    add(new ButtonPojo(){{BeanUtil.copyProperties(topButtonEnum.getAnEnum(), this);}});
                }};
                List<SaasSubButtonEnum> saasSubButtonEnumList = SaasSubButtonEnum.getByPermissionAlias(formDataListDTO.getSubBusinessType(),topButtonEnum,formDataListDTO.getLoginUser().getPermSet());
                saasSubButtonEnumList.forEach(item->{
                    subButtonList.add(new ButtonPojo(){{setAttr(item.getAlias());setValue(item.getName());}});
                });
                buttonPojo.setSubButtons(subButtonList);
            }
        }
        communicateVO.setTopPermissions(topButtonList);
    }

    /**
     * 设置范围筛选
     *
     * @param formDataListDTO
     * @throws
     * @author long.rao
     * @date 2020-03-18 17:01
     */
    private void rangeScreen(FormDataListDTO formDataListDTO) throws XbbException{
        JSONObject commonFilter = formDataListDTO.getCommonFilter();
        if (Objects.isNull(commonFilter)) {
            return;
        }
        JSONObject rangeScreen = commonFilter.getJSONObject(RangeScreenConstant.RANGE_SCREEN);
        if (Objects.isNull(rangeScreen) || Objects.isNull(rangeScreen.get(RangeScreenConstant.TYPE)) || StringUtil.isEmpty(rangeScreen.getString(RangeScreenConstant.TYPE)) || Objects.isNull(rangeScreen.get(RangeScreenConstant.VALUE))) {
            return;
        }

        String type;
        List<String> values;
        try {
            type = rangeScreen.getString(RangeScreenConstant.TYPE);
            values = rangeScreen.getJSONArray(RangeScreenConstant.VALUE).toJavaList(String.class);
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), "supplierCommunicateServiceimpl.rangeScreen中的commonFilter参数错误");
        }
        if (CollectionsUtil.isEmpty(values)) {
            return;
        }
        if (Objects.equals(type, RangeScreenConstant.DEPARTMENT)) {
            List<Long> deptIds = new ArrayList<>(values.size());
            values.forEach(item -> deptIds.add(Long.valueOf(item)));
            values = userModel.getUserIdsRecursionDep(deptIds, formDataListDTO.getCorpid(), 1, true);
        }

        List<ConditionsEntityExt> conditionsEntityExtList = formDataListDTO.getConditions();
        conditionsEntityExtList = conditionsEntityExtList == null ? new ArrayList<>() : conditionsEntityExtList;
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(CustomerCommunicateEnum.CREATOR_ID.getAttr(), "",
                CustomerCommunicateEnum.CREATOR_ID.getFieldType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
        conditionsEntityExtList.add(conditionsEntityExt);
        formDataListDTO.setConditions(conditionsEntityExtList);
    }
}
